from flask_restful import Resource, fields, marshal_with, request
import view.common as view_common
import view.submit as v_submit
import service.task_service as service
from utils.common.jwt_middleware import all_jwt_required
from exception.api_exception import APIException
import traceback
from enums.topic_view_status_enum import TopicViewStatusEnum


class Logs(Resource):
    """
   查看每一条数据的提交状态
   """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @all_jwt_required()
    @marshal_with(res_obj)
    def get(self):
        try:
            work_order_id = int(request.args.get("work_order_id"))
        except Exception as e:
            traceback.print_exc()
            raise APIException(message="参数错误")
        res = service.logs(work_order_id)
        return view_common.success(res=res)


class SendStatus(Resource):
    """
    查看发送状态
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @all_jwt_required()
    @marshal_with(res_obj)
    def get(self):
        data = request.args
        work_order_id_str = data.get("work_order_id")
        if work_order_id_str is None or work_order_id_str == "":
            return view_common.failed_10001(res="work_order_id is null or ''")
        work_order_id = int(work_order_id_str)
        b, res = service.search_send_status(work_order_id)
        if not b:
            return view_common.failed_10001(res=res)
        return view_common.success(res=res)


class Tasks(Resource):
    """
        停止当前任务
        """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    # @all_jwt_required()
    @marshal_with(res_obj)
    def get(self):
        res = service.tasks()  # 获取所有任务id
        return view_common.success(res=res)


class TaskStop(Resource):
    """
    停止当前任务
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @all_jwt_required()
    @marshal_with(res_obj)
    def post(self):
        data = request.get_json()
        work_order_id_str = data.get("work_order_id")
        if work_order_id_str is None or work_order_id_str == "":
            return view_common.failed_10001(res="work_order_id is null or ''")
        work_order_id = int(work_order_id_str)
        # res = service.task_stop(work_order_id)
        res = service.task_stop_v2(work_order_id)  # 远程停止
        return view_common.success(res=res)


class SearchTaskStatus(Resource):
    """
    查看任务运行状态
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @all_jwt_required()
    @marshal_with(res_obj)
    def get(self):
        data = request.args
        work_order_id_str = data.get("work_order_id")
        if work_order_id_str is None or work_order_id_str == "":
            return view_common.failed_10001(res="work_order_id is null or ''")
        work_order_id = int(work_order_id_str)
        res = service.search_task_status(work_order_id)
        return view_common.success(res=res)


class BuildTasks(Resource):
    """
    生成定时任务执行参数
    答题时间：问卷打开到提交的总时间（每一份问卷的答题时间） - 默认60-120
    连续处理次数：同一时间能发送多少行数据 - 8-12题 / 5秒内随机发送
    暂停时间：每批次数据打开的间隔时间 - 默认100-200秒
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @all_jwt_required()
    @marshal_with(res_obj)
    def post(self):
        """
        {
            "submit_type": "string", # 提交类型 -微信，浏览器...
            "answer_time_start": 0, # 一份问卷的答题开始时间
            "answer_time_end": 0, # 一份问卷的答题结束时间
            "single_answer_time_start": 0, # 单次答题-开始时间
            "single_answer_time_end": 0, # 单次答题-结束时间
            "can_answer_start": "string", # 可答题-开始时间
            "can_answer_end": "string", # 可答题-结束时间
            "is_base_order": true, # 是否乱序提交
            "area_rates": [ # 指定提交的区域
                {
                    "country": "string",
                    "province": "string",
                    "city": "string",
                    "rate": 0
                }
            ]
        }
        :return:
        """
        data = request.get_json()
        obj = v_submit.SendResults.model_validate(data)
        # res = service.build_tasks(data, obj, TopicViewStatusEnum.UN_SUBMIT.value)
        res = service.build_tasks_v2(data, obj, TopicViewStatusEnum.UN_SUBMIT.value)  # 远程发送
        return view_common.success(res=res)


class ResendResults(Resource):
    """
    重新提交未成功的问卷
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @all_jwt_required()
    @marshal_with(res_obj)
    def post(self):
        # d = {
        #     'work_order_id': data.get('work_order_id'),
        #     'item_answer_start': 10,
        #     'item_answer_end': 10,
        #     'deal_time_min': 10,
        #     'deal_time_max': 10,
        #     'interval_start': 10,
        #     'interval_end': 10,
        #     'is_base_order': True,
        # }
        data = request.get_json()
        obj = v_submit.SendResults.model_validate(data)
        # res = service.build_tasks(data, obj, TopicViewStatusEnum.FAILED_SUBMIT.value)
        res = service.build_tasks_v2(data, obj, TopicViewStatusEnum.FAILED_SUBMIT.value)  # 远程发送
        return view_common.success(res=res)


class TaskFinished(Resource):
    """
    任务完成
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @all_jwt_required()
    @marshal_with(res_obj)
    def post(self):
        try:
            data = request.get_json()
            work_order_id = int(data.get("work_order_id"))
        except Exception:
            traceback.print_exc()
            raise APIException(message="参数错误")
        res = service.task_finished(work_order_id)
        return view_common.success(res=res)


class TaskFinishedTime(Resource):
    """
    查询任务完成时间
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @all_jwt_required()
    @marshal_with(res_obj)
    def post(self):
        try:
            data = request.get_json()
            params = v_submit.JudgeSendDate.model_validate(data)
        except Exception:
            traceback.print_exc()
            raise APIException(message="参数错误")
        res = service.task_finished_time(params)
        return view_common.success(res=res)


class TaskWaitedSend(Resource):
    """
    任务完成
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @all_jwt_required()
    @marshal_with(res_obj)
    def post(self):
        try:
            data = request.get_json()
            work_order_id = int(data.get("work_order_id"))
        except Exception:
            traceback.print_exc()
            raise APIException(message="参数错误")
        res = service.task_waited_send(work_order_id)
        return view_common.success(res=res)
